/**
 * Package:com.goldcitynet;
 * $Id: SceneMapLoader.java,v 1.14 2009/03/30 11:08:01 yangc Exp $
 * Copyright(c) 2001-2005 www.afteryuan.com
 */
package com.afteryuan.server.data.impl;

import com.afteryuan.server.data.SceneLoader;
import com.goldcitynet.engine.model.Scene;
import com.goldcitynet.engine.model.SceneData;
import com.goldcitynet.engine.service.SceneService;
import com.goldcitynet.engine.service.SceneDataService;
import com.goldcitynet.util.PaginationBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

/**
 * SceneMapLoader 初始化场景工具
 * <p/>
 * <p><a href="SceneMapLoader.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@afteryuan.com">$Author: yangc $</a>
 * @version $Revision: 1.14 $
 */
public class SceneLoaderImpl implements SceneLoader {
    private static Log log = LogFactory.getLog(SceneLoaderImpl.class);
    private SceneService sceneService;
    private SceneDataService sceneDataService;

    public void setSceneService(SceneService sceneService) {
        this.sceneService = sceneService;
    }

    public void setSceneDataService(SceneDataService sceneDataService) {
        this.sceneDataService = sceneDataService;
    }

    public int[][] getSceneData(String keyword) {
        return sceneDataMap.get(keyword);
    }

    /**
     * 初始化所有场景
     */
    public void init() {
        List<Scene> scenes = sceneService.getAll();//取得所有场景
        if (scenes == null || scenes.size() == 0) {
            log.warn("Warn！There is not Scene in database！");
            return; //如果数据库没有场景数据，直接返回
        }

        for (Scene scene : scenes) {
        	//if("4028810a219960980121996bfb700002".equals(scene.getId()))
                initSingleScene(scene, sceneDataMap);
        }
    }

    /**
     * 初始化单个场景
     *
     * @param scene    场景对象
     * @param sceneMap 所有场景地图索引，用于存储单个已初始化好的场景
     */
    private void initSingleScene(Scene scene, Map<String, int[][]> sceneMap) {
        long sta = new Date().getTime();
        log.info("initing scene :" + scene.getName());

        int[][] map = new int[56][56];
        List<SceneData> sceneDatas = sceneDataService.list(scene);
        if(sceneDatas != null) {
        	for(int i=0 ; i<56 ; i++){
        			Arrays.fill(map[i],-1);
        	}

            for (SceneData data : sceneDatas) {
                map[data.getOy() + 22][data.getOx()] = data.getDepth();
            }
        }
        sceneMap.put(scene.getId(), map);
        
        long en = new Date().getTime();
        log.info("scene :" + scene.getName() + " inited.");
        log.debug ("scene " + scene.getName() + " expends：" + (en - sta));
    }

    private int[][] getMap(String sceneId) {
        return sceneDataMap.get(sceneId);
    }

}
